#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

#define FILE_COUNT 10000

size_t sprint_int(char *buf, int val)
{
	size_t nbytes = 0;
	int tmp = val;
	char *p;

	do {
		tmp /= 10;
		nbytes++;
	} while (tmp != 0);
	
	p = buf + nbytes - 1;
	while (p >= buf) {
		tmp = val % 10;
		val /= 10;
		*p-- = '0' + tmp;
	}
	
	return nbytes;
}

int main()
{
	char filename[100];
	char *text_buf;
	char *p;
	int i, j;
	int fd;
	size_t count = 0;
	int nbytes;

	mode_t f_attr;
	f_attr = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;

	text_buf = malloc(FILE_COUNT * 100);
	for (i = 0; i < FILE_COUNT; i++) {
		sprintf(filename, "out/r_c_%d", i);		
		fd = open(filename, O_RDWR | O_CREAT, f_attr);
		if (fd < 0) {
			perror("create failed");
			exit(EXIT_FAILURE);
		}

		p = text_buf;
		count = 0;
		for (j = 0; j < FILE_COUNT; j++) {
/*
			nbytes = sprintf(p, "%d\t%d\t%d\t%d\n", 
					rand() % FILE_COUNT + 1,
					rand() % FILE_COUNT + 1,
					rand() % FILE_COUNT + 1,
					rand() % FILE_COUNT + 1,
					rand() % FILE_COUNT + 1);
			if (nbytes <= 0) {
				perror("oome");
				exit(EXIT_FAILURE);
			}
*/
			nbytes = sprint_int(p, rand() % FILE_COUNT + 1);
			count += nbytes + 1;
			p += nbytes;
			*p++ = '\t';

			nbytes = sprint_int(p, rand() % FILE_COUNT + 1);
			count += nbytes + 1;
			p += nbytes;
			*p++ = '\t';

			nbytes = sprint_int(p, rand() % FILE_COUNT + 1);
			count += nbytes + 1;
			p += nbytes;
			*p++ = '\t';

			nbytes = sprint_int(p, rand() % FILE_COUNT + 1);
			count += nbytes + 1;
			p += nbytes;
			*p++ = '\t';

			nbytes = sprint_int(p, rand() % FILE_COUNT + 1);
			count += nbytes + 1;
			p += nbytes;
			*p++ = '\n';

		}
		write(fd, text_buf, count);
		close(fd);
	}
	free(text_buf);
	return 0;
}
